function is_expected_architecture() {
  if [ $(uname -m) != "$1" ]; then
    echo -e "\033[1;31;1mThe current script only supports execution on $1 architecture.\033[0m"
    return 1
  fi
}

function set_script_dir() {
  local REL_SCRIPT_DIR
  REL_SCRIPT_DIR="$(dirname "${BASH_SOURCE[0]}")" || return 1
  SCRIPT_DIR="$(cd "${REL_SCRIPT_DIR}" && pwd)" || return 1
}

function delete_a_directory_or_file() {
  if [ -e "$1" ]; then
    rm -rf "$1" || return 1
  fi
}

function safely_create_a_directory() {
  delete_a_directory_or_file "$1"
  mkdir "$1" || return 1
}

function conda_initialize() {
  __conda_setup="$("$1/bin/conda" 'shell.bash' 'hook' 2>/dev/null)"
  if [ $? -eq 0 ]; then
    eval "$__conda_setup"
  else
    if [ -f "$1/etc/profile.d/conda.sh" ]; then
      . "$1/etc/profile.d/conda.sh"
    else
      export PATH="$1/bin:$PATH"
    fi
  fi
  unset __conda_setup
}

function create_and_activate_conda_env() {
  conda deactivate || return 1
  conda env remove -n kallisto -y || return 1
  conda create -n kallisto -c "$1" kallisto=0.48.0 -y || return 1
  conda activate kallisto || return 1
}

function generate_execution_result_data() {
  EXPECTED_DIR="${SCRIPT_DIR}/Expected"
  safely_create_a_directory "$1" || return 1
  kallisto >"$1/kallistoUsage"

  kallisto index -i "$1/transcripts.idx" "$2/transcripts.fasta.gz"

  kallisto quant -i "$1/transcripts.idx" -o "$1/outputQuantification" \
    -b 100 "$2/reads_1.fastq.gz" "$2/reads_2.fastq.gz"

  kallisto quant -i "$1/transcripts.idx" -o "$1/outputSingleEndReads" \
    -b 100 --single -l 180 -s 20 "$2/reads_1.fastq.gz"

  kallisto quant -i "$1/transcripts.idx" -b 30 -o "$1/outputGenomebam" \
    --genomebam --gtf "$2/transcripts.gtf.gz" --chromosomes \
    "$2/chrom.txt" "$2/reads_1.fastq.gz" "$2/reads_2.fastq.gz"
}

function generate_HDF5_intermediate_alignment_files() {
  for i in "$@"; do
    for j in "$i/outputGenomebam" "$i/outputQuantification" "$i/outputSingleEndReads"; do
      if [ ! -e "$j" ]; then
        echo -e "\033[1;31;1mThe current path does not exist. [$j]\033[0m"
        return 1
      fi
      delete_a_directory_or_file "$j/abundance.h5.ali"
      # To use h5dump, kallisto needs to be installed in the conda environment.
      h5dump "$j/abundance.h5" >"$j/abundance.h5.ali"
      if [ $? -eq 1 ]; then
        echo -e "\033[1;31;1mh5dump execution failed,Please rerun the current script.\033[0m"
        return 1
      fi
    done
  done
}

function print_execution_result() {
  if [ "$1" -eq 0 ]; then
    echo -e "\033[1;32;1m'$2' executed successfully.\n\033[0m"
  else
    echo -e "\033[1;31;1m'$2' execution result does not match expected result.\n\033[0m"
    return "$1"
  fi
}

function compare_file_content_by_diff() {
  diff "$1" "$2" >/dev/null
  print_execution_result "$?" "$3" || return 1
}

function compare_file_content_by_cmp() {
  cmp "$1" "$2" >/dev/null
  print_execution_result "$?" "$3" || return 1
}
